package org.weed.remote.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

import org.weed.remote.network.server.StreamServer;

public class StockTrac extends JFrame implements PriceChangeListener {
	private JTextArea textArea;
	private JTable table;
	private DefaultTableModel tableModel;
	private Map<String, Integer> cellLookup;
	private ExecutorService executor;
	
	public StockTrac() {
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLocationRelativeTo(null);
		this.setTitle("StockTrac");
		this.setSize(300, 300);
		
		tableModel = new DefaultTableModel();
		tableModel.addColumn("Stock");
		tableModel.addColumn("Price");
		table = new JTable(tableModel);
		DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
		renderer.setHorizontalAlignment(SwingConstants.CENTER);
		table.getColumn("Stock").setCellRenderer(renderer);
		table.getColumn("Price").setCellRenderer(renderer);
		this.add(new JScrollPane(table), BorderLayout.CENTER);
		
		textArea = new JTextArea();
		textArea.setFont(new Font("Book Antiqua", Font.PLAIN, 30));
		textArea.setAlignmentX(RIGHT_ALIGNMENT);
		textArea.setText("-");
		this.getContentPane().add(textArea, BorderLayout.SOUTH);
		
		cellLookup = new HashMap<String, Integer>();
		
		executor = Executors.newSingleThreadExecutor();
		executor.execute(new StreamServer(80) {
			@Override
			public void processLine(String line) {
				//System.out.println(line);
				if (line.startsWith("GET")) {
					int startPos = line.indexOf("?") + 1;
					int andPos =  line.indexOf("&");
					int endPos = line.indexOf("HTTP") - 1;
					String stockCode = line.substring(startPos, andPos).split("=")[1];					
					String priceStr = line.substring(andPos+1, endPos).split("=")[1];
					updatePrice(stockCode, Double.parseDouble(priceStr));
					try {
						getClient().close();
					} catch (IOException e) {
					}
				}
			}
		});
	}
	
	public void addStock(String stockCode) {
		tableModel.addRow(new Object[] {stockCode, "-"});
		tableModel.fireTableDataChanged();
		cellLookup.put(stockCode, tableModel.getRowCount() - 1);
//		try {
//			scheduler.scheduleAtFixedRate(new SimpleHttpConnection(stockCode, "http://tw.stock.yahoo.com/q/q?s=" + stockCode, this), 0, 30, TimeUnit.SECONDS);
//		} catch (MalformedURLException e) {
//			System.err.println("Unable to add stock: " + stockCode);
//		}
	}
	
	public void updatePrice(String stockCode, double price) {
		//System.out.println(stockCode+":"+price);
		int row =  cellLookup.get(stockCode);
		tableModel.setValueAt(price, row, 1);
		DefaultTableCellRenderer renderer = (DefaultTableCellRenderer) table.getCellRenderer(row, 1);
		if (price > 0) {
			renderer.setForeground(Color.red);
		} else if (price < 0) {
			renderer.setForeground(Color.green);
		} else {
			renderer.setForeground(Color.black);
		}
		updateTotal();
	}
	public synchronized void updateTotal() {
		int rows = table.getRowCount();
		
		double total = 0;
		for (int row = 0; row < rows; row++) {			
			Double value = null;			
			try {				
				value = Double.parseDouble(""+ tableModel.getValueAt(row, 1));
			} catch (Exception e) {
			}
			
			if (value != null) {
				total += value;
			}
		}
		if (total > 0) {
			textArea.setForeground(Color.red);
		} else if (total < 0) {
			textArea.setForeground(Color.green);
		} else {
			textArea.setForeground(Color.black);
		}
		textArea.setText(""+total);
	}
	
	public static void main(String[] args) throws InterruptedException {
		//System.setProperty("http.proxyHost", "BNESPROXY");
		//System.setProperty("http.proxyPort", "8080");
		
		StockTrac stockTrac = new StockTrac();
		stockTrac.addStock("2498");
		stockTrac.addStock("3008");
		stockTrac.addStock("3231");
		stockTrac.addStock("5483");
		
		
		
		
		stockTrac.setVisible(true);
//		Thread.sleep(2000);
//		stockTrac.updatePrice("2498", 100);
//		Thread.sleep(2000);
//		stockTrac.updatePrice("3008", -100);
//		Thread.sleep(2000);
//		stockTrac.updatePrice("5483", 0);
		
	}


}
